package com.es.springbootesdemo.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.es.springbootesdemo.domain.BulkUser;
import com.es.springbootesdemo.domain.User;

/**
 * @author: yushizhong
 * @date: 2022-01-19 11:12
 * @version: 1.0
 **/
@RestController
@RequestMapping("/es")
public class ElasticSearchController {

    @Resource
    private RestHighLevelClient client;

    /**
     * 数据添加到ES
     *
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public HttpEntity addUser(@RequestBody User user) throws IOException {

        IndexRequest request = new IndexRequest("user", "ysz");
        // request.id("3");
        request.timeout("1s");
        request.source(JSON.toJSONString(user), XContentType.JSON);

        IndexResponse resp = client.index(request, RequestOptions.DEFAULT);
        System.out.println("添加文档-------" + JSON.toJSONString(resp));

        return new HttpEntity(resp.getResult().getLowercase().equals("created"));

    }

    /**
     * 删除
     *
     * @param id
     * @return
     * @throws IOException
     */
    @DeleteMapping("/{id}/delete")
    public HttpEntity deleteUser(@PathVariable("id") String id) throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("user", "ysz", id);
        deleteRequest.timeout("1s");

        DeleteResponse resp = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println("测试删除文档------" + resp.status());

        return new HttpEntity("OK".equals(resp.status()));
    }

    /**
     * 批量增加
     */

    @PostMapping("/batch-add")
    public HttpEntity bulkAddUsers(@RequestBody BulkUser bulkUser) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("1s");
        for (User user : bulkUser.getUserList()) {
            bulkRequest.add(new IndexRequest("user").type("ysz").source(JSON.toJSONString(user), XContentType.JSON));
        }

        BulkResponse resp = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("测试批量添加文档-----" + resp.hasFailures());
        return new HttpEntity(!resp.hasFailures());
    }

    /**
     * 修改数据
     *
     * @param user
     * @param id
     * @return
     * @throws IOException
     */
    @PostMapping("/update")
    public HttpEntity updateUser(@RequestBody BulkUser user, @RequestParam(value = "id") String id) throws IOException {
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.index("user").type("ysz").timeout("1s").id(id).doc(JSON.toJSONString(user), XContentType.JSON);
        UpdateResponse resp = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println("测试修改文档-----" + resp.status());
        return new HttpEntity("OK".equals(resp.status()));

    }

    /**
     * 查询es所有用户
     */
    @GetMapping("/user/list")
    public BulkUser getUsers() throws IOException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.from(0).size(100).timeout(new TimeValue(60, TimeUnit.SECONDS));
        // sourceBuilder.fetchSource(new String[] {"fields.name", "fields.sex", "fields.age"}, new String[] {});
        SearchRequest searchRequest = new SearchRequest("user");
        searchRequest.types("ysz").source(sourceBuilder);
        SearchResponse resp = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = resp.getHits();
        SearchHit[] searchHits = hits.getHits();
        List<User> users = new ArrayList<>();
        for (SearchHit searchHit : searchHits) {
            String aa = searchHit.getSourceAsString();
            User sourceUser = JSONObject.parseObject(searchHit.getSourceAsString(), User.class);
            System.out.println(sourceUser);
            users.add(sourceUser);
        }

        BulkUser bulkUser = new BulkUser();
        bulkUser.setUserList(users);
        return bulkUser;
    }

}
